import axios from "axios";

const request = axios.create({
    baseURL: '/api',
    timeout: 5000,
});

const refreshToken = async () => {
    try {
        const refreshToken = localStorage.getItem('refresh_token');
        const response = await request.get(`/users/refresh/${refreshToken}`);
        console.log(response);
        const access_token = response.data.data.access_token;
        const refresh_token = response.data.data.refresh_token;

        // 假设您使用的是localStorage存储Token
        localStorage.setItem('access_token', access_token);
        localStorage.setItem('refresh_token', refresh_token);

        // 更新axios默认的Token
        const newToken = localStorage.getItem('access_token');
        request.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
    } catch (error) {
        // 如果刷新Token失败，可以进行相应的错误处理
        console.error('Token refresh failed', error);
    }
};

request.interceptors.request.use((config) => {
    const token = localStorage.getItem('access_token');
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

request.interceptors.response.use(
    response => response,
    async error => {
      const originalRequest = error.config;      
      if (error.response.status === 401 || error.response.status === 403 && !originalRequest._retry) {
        originalRequest._retry = true;
        // 检查Token是否过期，如果是则尝试刷新
        await refreshToken();
        // 刷新后重新发起请求
        return request(originalRequest);
      }
      return Promise.reject(error);
    }
  );

export default request;
